package com.example.tass.controller;

import cn.tass.SRJ1933.devices.inf.TassSignServerApi;
import cn.tass.SRJ1933.devices.params.request.other.CharsetConvertRequest;
import cn.tass.SRJ1933.devices.params.response.other.CharsetConvertResponse;
import cn.tass.SRJ1933.devices.params.response.other.HeartBeatResponse;
import cn.tass.exceptions.TAException;
import com.example.tass.common.ResultMessage;
import com.example.tass.constant.Constants;
import com.example.tass.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

// 3.12 其它功能
@RestController
public class HeartBeat_2_12 {

    private static String printFormat = "错误码[%d]\n错误消息[%s]\n接口结果： %s\n";
    private static final Logger logger = LoggerFactory.getLogger(HeartBeat_2_12.class);
    private TassSignServerApi signServerApi;

    public HeartBeat_2_12(TassSignServerApi signServerApi) {
        this.signServerApi = signServerApi;
    }

    // 3.12.1 心跳检测
    @GetMapping(value = "/heartBeat")
    public ResultMessage heartBeat() {
        try {
            HeartBeatResponse response = signServerApi.heartBeat();
            if (response.getCode() == 0) {
                return ResultMessage.newSuccessResult(Constants.HEART_BEAT_SUCCESS+"，服务器当前时间是："+response.getTime());
            } else {
                return ResultMessage.newFailureResult("心跳检测失败.");
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }

    // 3.12.2 字符编码转换
    @GetMapping(value = "/charsetConvert")
    public ResultMessage charsetConvert(@RequestBody CharsetConvertRequest request) {
        String data = request.getData();
        try {
            if (!StringUtils.isBase64(request.getData())) {
                data = StringUtils.stringToBase64String(data,request.getSrcCharSet());
            }
            CharsetConvertResponse response = signServerApi.charsetConvert(request.getSrcCharSet(), request.getDstCharSet(), data);
            if (response.getCode() == 0) {
                if(StringUtils.isBase64(data)){
                    data = StringUtils.Base64ToString(data);
                }
                return ResultMessage.newSuccessResult("字符编码转换成功."+"，转换前的字符串是"+data+"，转换后的字符串是："+response.getResult());
            } else {
                return ResultMessage.newFailureResult("心跳检测失败.");
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }
}
